function dq(x){
    return document.querySelectorAll(x);
}
let main = dq(".main")[0],
    img =dq(".img_box")[0],
    sec = dq(".sec > span"),
    imgl=dq(".img_box>li").length,
    carousel = dq(".carousel")[0],
    num=0,//计数变量
    lastIndex=0,//上一个操作下标
    timer;

main.addEventListener("click",function(e){
    (e.target.className == "left")&& lt();
    (e.target.className == "right")&&rt();
})

// 下一张
function rt(){
     num++;
    if(num === imgl-2){
        setTimeout(function(){
            num=0;
            img.style.left="-620px";
            img.style.transition="none";
        },1000)
    } 
    img.style.transition="1s ease";
    img.style.left=`-${(num+1)*620}px`;
    sec[lastIndex].classList.remove("active");
    sec[num].classList.add("active");
    lastIndex=num;
};

// 上一张
function lt(){
    num--;
    if(num === -1){
        setTimeout(function(){
            img.style.transition="none";
            num=imgl-3;
            img.style.left=`-${(4)*620}px`;
        },1000)
    }
    img.style.transition="1s ease";
    img.style.left=`-${(num+1)*620}px`;
    sec[lastIndex].classList.remove("active");
    sec[num].classList.add("active");
    lastIndex=num;
};

// 底部圆点
sec.forEach(function(val,num){
    val.addEventListener("mouseover",function (){
        img.style.left=`-${(num+1)*620}px`;
        sec[lastIndex].classList.remove("active");
        sec[num].classList.add("active");
        lastIndex=num;
    })
});

// 自动轮播
timeFn();
function timeFn() {
    if (timer) {
        clearInterval(timer);
    }
    timer = setInterval(function () {
        rt();
    }, 2000);
}

// 鼠标移入，停止定时器
carousel.addEventListener("mouseover", function () {
    clearInterval(timer);
});
// 鼠标移出开始定时器
carousel.addEventListener("mouseleave", function () {
    setTimeout(timeFn, 1000)
});

// 检测页面是否切换，切换就停止定时器
window.addEventListener("visibilitychange", function () {
    if (document.hidden) {
        clearInterval(timer);
    } else {
        timeFn();
    }
});